import {
  addPurchase,
  addPurchaseall,
  delPurchase,
  delPurchasecall,
  queryOrdernumber,
  queryPurchasecalList,
  queryPurchaselist,
  updatePurchase,
} from "@/services/purchase";
import { querySupplierList } from "@/services/supplier";
import { uploadUrl } from "@/untils";
import {
  DrawerForm,
  ProFormDatePicker,
  ProFormDigit,
  ProFormGroup,
  ProFormSelect,
  ProFormText,
  ProFormUploadButton,
  ProTable,
} from "@ant-design/pro-components";
import { Button, Form, Image, message, Popconfirm } from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
export const imgConfig = {
  url: "http://admin.lianhongtech.com/uploads/",
};

const PurchaseOrder = () => {
  const { url } = imgConfig;
  const [open, setOpen] = useState<boolean>(false);
  const [putInOpen, setPutInOpen] = useState<boolean>(false);
  const [putInDetailOpen, setPutInDetailOpen] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [currentId, setCurrentId] = useState<number | null>(null); // 当前采购订单 id
  const [currentData, setCurrentData] = useState<any>([]);
  const [supplierList, setSupplierList] = useState<any>([]);
  const [productList, setProductList] = useState<any>([]);
  const [orderNumber, setOrderNumber] = useState<string>("");
  const [currentType, setCurrentType] = useState<string>(""); // 当前采购弹窗的状态 编辑或者新建
  const [fileList, setFileList] = useState<any>([]); // 发票
  const [filePiciList, setFilePiciList] = useState<any>([]); // 送货单
  const [putInDetailType, setPutInDetailType] = useState<string>("");
  const actionRef: any = useRef(null);

  // 生成批次入库号
  const queryPurchaseNumber = async () => {
    const res = await queryOrdernumber({ type: 2 });
    if (res?.success) {
      setOrderNumber(res?.result?.generateordernumber);
      form.setFieldValue("batch_order", res?.result?.generateordernumber);
    } else {
      message.error("入库批次号生成失败，请稍后再试");
    }
  };
  useEffect(() => {
    if (!putInOpen) {
      setFilePiciList([]);
    } else {
      queryPurchaseNumber();
    }
  }, [putInOpen]);
  // 删除入库明细的某一条
  const handleDel = async (id: number) => {
    const res = await delPurchasecall({ id });
    if (res?.success) {
      message.success("操作成功");
      getPurchasecalList(id);
    } else {
      message.error("操作失败，请联系管理员");
    }
  };

  // 采购订单操作
  const handlePurchase = (record: any, type: string) => {
    setCurrentId(record.id);
    const {
      invoice_pic,
      pur_order: purchase_order,
      pur_num: purchase_num,
      pur_price: purchase_price,
      sup_name: supplier_name,
      contract_time,
      pro_name,
      unit,
    } = record;
    setOpen(true);
    setCurrentType(type);
    const products =
      supplierList.find(
        (v: { supplier_name: string }) => supplier_name === v.supplier_name
      )?.product_name || "";
    const list = products
      .split(",")
      ?.map((v: string) => ({ label: v, value: v }));
    setProductList(list);
    const picList = invoice_pic?.length
      ? invoice_pic?.split(",")?.map((v: any) => imgConfig?.url + v)
      : [];
    const list1 = picList.map((url, i) => ({
      uid: `-${i}`,
      url,
      name: `img_${i}`,
      status: "done",
    }));
    setFileList(list1);
    form.setFieldsValue({
      purchase_order,
      purchase_num: purchase_num.toString(),
      purchase_price: purchase_price.toString(),
      contract_time: dayjs(contract_time * 1000).format("YYYY-MM-DD"),
      supplier_name: supplierList?.find(
        (v: { supplier_name: string }) => v.supplier_name === supplier_name
      )?.id,
      product_name: pro_name.split(","),
      unit,
      pic: list1,
    });
  };
  // 入库明细
  const putInColumns = [
    {
      title: "批次",
      dataIndex: "batch_order",
      key: "batch_order",
      width: 180,
    },
    {
      title: "实际到货日期",
      dataIndex: "arr_time",
      key: "arr_time",
      width: 200,
      render: (time: string) =>
        dayjs(Number(time) * 1000).format("YYYY-MM-DD hh:mm"),
    },
    {
      title: "入库数量",
      dataIndex: "num",
      key: "num",
      width: 80,
    },
    {
      title: "系统入库日期",
      dataIndex: "pur_time",
      key: "pur_time",
      width: 180,
      render: (time: string) => dayjs(Number(time) * 1000).format("YYYY-MM-DD"),
    },
    {
      title: "送货单",
      dataIndex: "delivery_note_pic",
      key: "delivery_note_pic",
      width: 180,
      render: (delivery_note_pic: string) => (
        <Image width={100} height={100} src={url + delivery_note_pic} />
      ),
    },
    {
      title: "操作",
      key: "action",
      search: false,
      width: 180,
      fixed: "right",
      render: (_, record) => (
        <>
          <a
            style={{ marginRight: 8 }}
            onClick={() => {
              setOpen(true);
              setPutInDetailType("edit");
            }}
          >
            编辑
          </a>
          <Popconfirm
            title="提示"
            description="确认删除该入库记录吗？"
            onConfirm={() => handleDel(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <a style={{ marginRight: 8 }}>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];
  // 表格列配置
  const columns = [
    {
      title: "采购订单号",
      dataIndex: "pur_order",
      key: "pur_order",
      width: 180,
      fixed: "left",
      search: false,
    },
    {
      title: "产品名称",
      dataIndex: "pro_name",
      key: "pro_name",
      width: 120,
      // render: (text) => <a>{text}</a>,
    },
    // {
    //   title: "产品单价(元)",
    //   dataIndex: "pur_price",
    //   key: "pur_price",
    //   width: 120,
    //   search: false,
    //   align: "right",
    // },
    {
      title: "产品采购数量",
      dataIndex: "pur_num",
      key: "pur_num",
      width: 120,
      search: false,
      align: "right",
      render: (text: any, record: any) => `${text}${record.unit}`,
    },
    // {
    //   title: "产品实际到货数量",
    //   dataIndex: "quantity",
    //   key: "quantity",
    //   width: 140,
    //   search: false,
    //   align: "right",
    //   render: (text: any, record: any) => text || `${text}${record.unit}`,
    // },
    {
      title: "供应商名称",
      dataIndex: "sup_name",
      key: "sup_name",
      width: 200,
      search: true,
    },
    {
      title: "合同开始时间",
      dataIndex: "contract_time",
      key: "contract_time",
      search: false,
      width: 140,
      render: (time: string) => dayjs(Number(time) * 1000).format("YYYY-MM-DD"),
    },
    {
      title: "订单创建时间",
      dataIndex: "create_time",
      key: "create_time",
      search: false,
      width: 180,
      render: (time: string) =>
        dayjs(Number(time) * 1000).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "最新入库时间",
      dataIndex: "new_time",
      key: "new_time",
      width: 140,
      search: false,
      render: (time: string) =>
        time === "-" || time === "0"
          ? "-"
          : dayjs(Number(time) * 1000).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "已入库数量",
      dataIndex: "inventory_num",
      key: "inventory_num",
      width: 120,
      search: false,
      align: "right",
      render: (text: any, record: any) => `${text}${record?.unit}`,
    },
    {
      title: "采购状态",
      dataIndex: "status",
      key: "status",
      width: 100,
      fixed: "right",
      align: "center",
      valueEnum: {
        0: { text: "待采购", status: "Default" },
        1: { text: "入库中", status: "Processing" },
        2: { text: "已完成", status: "Success" },
      },
    },
    {
      title: "操作",
      key: "action",
      search: false,
      width: 280,
      fixed: "right",
      render: (_: any, record: any) => (
        <>
          <a
            style={{ marginRight: 8 }}
            onClick={() => handlePurchase(record, "edit")}
          >
            编辑
          </a>
          <a
            style={{ marginRight: 8 }}
            onClick={() => handlePurchase(record, "detail")}
          >
            查看
          </a>
          <a style={{ marginRight: 8 }} onClick={() => handlePutIn(record.id)}>
            入库
          </a>
          <a
            style={{ marginRight: 8 }}
            onClick={() => handlePutInDetail(record)}
          >
            查看入库
          </a>
          <Popconfirm
            title="提示"
            description="确定删除该采购订单吗？不可恢复！"
            onConfirm={() => handleDelPurchase(record?.id)}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  // 请求列表
  const fetchData = async (values: any) => {
    const {
      current: page,
      pageSize: pagesize,
      sup_name: supplier_name,
      status,
      pro_name: product_name,
    } = values;
    const params = {
      page,
      pagesize,
      supplier_name,
      product_name,
      purchase_status: !isNaN(status) ? Number(status) : undefined,
    };
    const res = await queryPurchaselist(params);
    return {
      data: res?.result?.data || [],
      total: res?.result?.total || 0,
      success: true,
    };
  };

  const getSupplierList = async () => {
    const params = {
      page: 1,
      pagesize: 999,
    };
    const res = await querySupplierList(params);
    if (res?.success) {
      setSupplierList(res.result?.data || []);
    } else {
      message.error("获取供应商列表失败，请联系管理员");
    }
  };

  // 采购入库
  const handlePutIn = (e: number) => {
    setPutInOpen(true);
    setCurrentId(e);
  };

  // 请求批次列表
  const getPurchasecalList = async (id: number) => {
    const res = await queryPurchasecalList({ id, page: 1, pagesize: 999 });
    if (res?.success) {
      setCurrentData(res.result?.data || []);
    }
  };

  // 查看入库明细
  const handlePutInDetail = (record: any) => {
    setPutInDetailType("details");
    setPutInDetailOpen(true);
    setCurrentId(record.id);
  };
  // 删除采购订单
  const handleDelPurchase = async (id: number) => {
    const res = await delPurchase({ id });
    if (res?.success) {
      message.success("操作成功");
      actionRef?.current?.reload();
    } else message?.error("操作失败，请稍后再试");
  };
  // 生成订单号
  const queryOrderNumber = async () => {
    const res = await queryOrdernumber({ type: 1 });
    if (res?.success) {
      setOrderNumber(res?.result?.generateordernumber);
      form.setFieldValue("purchase_order", res?.result?.generateordernumber);
    } else {
      message.error("合同编号生成失败，请稍后再试");
    }
  };
  useEffect(() => {
    getSupplierList();
  }, []);
  useEffect(() => {
    if (putInDetailOpen && currentId) {
      getPurchasecalList(currentId);
    }
    if (putInDetailOpen && putInDetailType === "edit") {
      queryOrderNumber();
    }
  }, [currentId, putInDetailOpen, putInDetailType]);

  useEffect(() => {
    if (!open) {
      setProductList([]);
    }
    if (open && currentType === "create") {
      queryOrderNumber();
    } else setOrderNumber("");
  }, [open, currentType]);
  const handleAdd = () => {
    setOpen(true);
    setCurrentType("create");
  };

  // 选择供应商
  const handleSupplier = (e: number) => {
    form.setFieldValue("product_name", undefined);
    if (!e) {
      setProductList([]);
      return;
    }
    const products =
      supplierList.find((v: { id: number }) => e === v.id)?.product_name || "";
    const list = products
      .split(",")
      ?.map((v: string) => ({ label: v, value: v }));
    setProductList(list);
  };
  // 新建采购订单
  const handlePurchaseIn = async (values: any) => {
    const {
      pic,
      contract_time,
      purchase_num,
      purchase_order,
      purchase_price,
      supplier_name,
      product_name,
      unit,
    } = values;
    const pics = pic
      ?.filter((item: any) => {
        return item?.response?.success || item?.status === "done";
      })
      ?.map((item: any) => item?.response?.result?.savename || item?.url)
      ?.join(",")
      ?.replace(imgConfig?.url, "");
    const params = {
      contract_time: dayjs(contract_time)?.unix(),
      purchase_num,
      unit,
      purchase_order,
      purchase_price,
      product_name: product_name?.join(","),
      supplier_name: supplierList?.find(
        (v: { id: string }) => v.id === supplier_name
      )?.supplier_name,
      pic: pics,
      id: currentType === "edit" ? currentId : undefined,
    };
    const res =
      currentType === "edit"
        ? await updatePurchase(params)
        : await addPurchase(params);
    if (res?.success) {
      message?.success(currentType === "edit" ? "编辑成功" : "新建成功");
      setOpen(false);
      actionRef?.current?.reload();
    } else {
      message?.error(
        `${currentType === "edit" ? "编辑" : "新建"}采购订单失败，请稍后再试`
      );
    }
  };
  // 批次入库
  const handlePutInSubmit = async (values: any) => {
    const { arrve_time, num, pic_songhuodan, batch_order } = values;
    const pics = pic_songhuodan
      ?.filter((item: any) => {
        return item?.response?.success;
      })
      ?.map((item: any) => item?.response?.result?.savename)
      ?.join(",");
    const params = {
      pic: pics,
      batch_order,
      arrve_time: dayjs(arrve_time)?.unix(),
      num,
      purchase_order_id: currentId,
    };
    const res = await addPurchaseall(params);
    if (res?.success) {
      message.success("入库成功");
      setPutInOpen(false);
      actionRef?.current?.reload();
    } else {
      message?.error("操作失败，请稍后再试");
    }
  };

  return (
    <>
      <ProTable
        columns={columns as any}
        request={fetchData}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        scroll={{ x: 1500 }}
        options={false}
        toolBarRender={() => [
          <Button key="add" type="primary" onClick={handleAdd}>
            新建采购订单
          </Button>,
        ]}
        actionRef={actionRef}
      />
      <DrawerForm
        width={800}
        open={open}
        title={`${
          currentType === "create"
            ? "新建"
            : currentType === "edit"
            ? "编辑"
            : "查看"
        }采购订单`}
        form={form}
        autoFocusFirstInput
        disabled={currentType === "detail"}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => {
            setOpen(false);
            setCurrentType("");
          },
        }}
        onFinish={handlePurchaseIn}
        initialValues={{
          purchase_order: orderNumber,
        }}
      >
        <ProFormText
          width="sm"
          name="purchase_order"
          label="合同编号"
          tooltip="系统生成"
          disabled
          rules={[{ required: true }]}
        />
        <ProFormGroup>
          <ProFormDatePicker
            name="contract_time"
            label="合同开始日期"
            width="md"
            rules={[{ required: true }]}
          />
          <ProFormSelect
            showSearch
            width={"md"}
            options={supplierList?.map(
              (v: { supplier_name: string; id: string }) => ({
                label: v.supplier_name,
                value: v.id,
              })
            )}
            name="supplier_name"
            label="供应商"
            placeholder={"请选择供应商"}
            rules={[{ required: true }]}
            onChange={handleSupplier}
          />
        </ProFormGroup>

        <ProFormSelect
          width={"md"}
          options={productList}
          name="product_name"
          label="采购产品"
          showSearch
          mode="multiple"
          placeholder={"请选择采购产品"}
          rules={[{ required: true }]}
        />

        <ProFormDigit
          width="md"
          label="采购数量"
          name="purchase_num"
          min={0.01}
          max={99999999}
          rules={[{ required: true }]}
          fieldProps={{
            precision: 2,
            addonAfter: (
              <ProFormSelect
                noStyle
                initialValue={"吨"}
                name={"unit"}
                style={{ width: 60 }}
                options={[
                  { label: "吨", value: "吨" },
                  { label: "平方", value: "平方" },
                  { label: "个", value: "个" },
                ]}
              ></ProFormSelect>
            ),
          }}
        />
        <ProFormDigit
          width="md"
          label="产品单价(元)"
          name="purchase_price"
          min={0.01}
          max={99999999}
          rules={[{ required: true }]}
          fieldProps={{ precision: 2 }}
        />

        <ProFormUploadButton
          fieldProps={{
            fileList,
            listType: "picture-card",
            // onPreview: handlePreview,
            onChange: ({ fileList: newList }) => setFileList(newList),
          }}
          name="pic"
          label="上传发票"
          action={uploadUrl}
        />
      </DrawerForm>
      {/* 批次入库 */}
      <DrawerForm
        form={form}
        autoFocusFirstInput
        drawerProps={{
          destroyOnClose: true,
          onClose: () => setPutInOpen(false),
        }}
        onFinish={handlePutInSubmit}
        width={800}
        title="入库"
        open={putInOpen}
      >
        <ProFormText
          width="sm"
          name="batch_order"
          label="入库批次"
          tooltip="系统生成"
          disabled
          rules={[{ required: true }]}
        />
        <ProFormDigit
          width="md"
          label="本次入库数量"
          name="num"
          min={0.01}
          max={99999999}
          fieldProps={{ precision: 2 }}
          rules={[{ required: true }]}
        />
        <ProFormDatePicker
          name="arrve_time"
          label="实际到货日期"
          width="md"
          rules={[{ required: true }]}
        />
        <ProFormUploadButton
          rules={[{ required: true }]}
          fieldProps={{
            fileList: filePiciList,
            listType: "picture-card",
            // onPreview: handlePreview,
            onChange: ({ fileList: newList }) => setFilePiciList(newList),
          }}
          name="pic_songhuodan"
          label="送货单照片"
          action="http://admin.lianhongtech.com/index.php/erpupload/upload"
        />
      </DrawerForm>
      {/* 入库明细 */}
      <DrawerForm
        form={form}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => setPutInDetailOpen(false),
        }}
        submitter={false}
        width={1000}
        title="入库明细"
        open={putInDetailOpen}
      >
        <ProTable
          search={false}
          options={false}
          rowKey="id"
          columns={putInColumns as any}
          dataSource={currentData}
        />
      </DrawerForm>
    </>
  );
};

export default PurchaseOrder;
